package com.rcp.login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rcp.objects.EmployeeBean;

@WebServlet("/AuthenticateServlet")
public class AuthenticateServlet extends HttpServlet {

	private static int x = 3;
	
	// AuthenticateServlet is only used when a Employee clicks log in from the login page
	// A username and password is passed in from the login page and sent to AuthenticateServlet
	// If username and or password is blank or does not match any records, AuthenticateServlet will redirect to
	// login page with the correct error message

	// If username and password matches records from the ArrayList of Employees named Employee, it will redirect to
	// WelcomeServlet, but only after it has created a session for the current Employee with loggedIn to be true.

	// Also if Employee clicked remember me, it creates a cookie along with the session
	// Also note that a cookie only stores the username. I could always add more but to make it simple a username
	// is only thing that is passed in.

	private static final long serialVersionUID = 1L;
	private static final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
//	private static String dt;

	public void init() throws ServletException {

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// Check for anything that needs to be processed
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String rememberMe = request.getParameter("rememberMe");

		String pathToView = "/WEB-INF/login/Login.jsp";
		
		if(request.getParameter("reset") != null){
			
			x = 3;
			request.setAttribute("reset", null);
			
		}
		
		if(x <= 0){
			
			HttpSession session = request.getSession();
			// Create the Session variables
			session.setAttribute("deadpage", true);
			pathToView = "/WEB-INF/login/DeadPage.jsp";
			
		} else {
		
			// Check for errors
			if(username == null || password == null 
					|| username.trim().length() == 0 || password.trim().length() == 0){
				
				pathToView = "/WEB-INF/login/Login.jsp";
				
			}else{
	
				// Define connection variables
				String className = "com.mysql.jdbc.Driver";
				//String url		 = "jdbc:mysql://cs3.calstatela.edu:8080/cs437group01";
				String url		 = "jdbc:mysql://cs3.calstatela.edu:3306/cs437group01";
				String dbusername  = "cs437group01";
				String dbpassword  = "VHj#dj!v";
	
				try{
					// Include the driver class
					Class.forName( className );
	
					// Establish a connection to the database
					Connection connection =
							DriverManager.getConnection(url, dbusername, dbpassword);
	
					// Create the query
					String query =	"SELECT * FROM Employees WHERE username = '" + username.toString() + "'  AND  password = '"+password.toString()+"'";
	
					// Get a reference to the statement object that will execute our query
					// on the server
					Statement statement = connection.createStatement();
	
					// Execute the query and Store the returned records (ResultSet)
					ResultSet resultSet = statement.executeQuery(query);
	
					if(resultSet == null) {
						
						x--;
						
						request.setAttribute("numberOfTriesLeft", x);
						request.setAttribute("action", "message1");

						pathToView = "/WEB-INF/login/Login.jsp";
						
					}
					
					String tmpPass ="";
					String tmpUID = "";
					String tmpUsername = "";
					
					EmployeeBean user = null;
					
					while ( resultSet.next() ){
	
						user = new EmployeeBean(resultSet.getInt("EmployeeID"), resultSet.getString("FirstName"), resultSet.getString("LastName"), resultSet.getInt("status"));
						tmpUsername = resultSet.getString("username");
						tmpUID = resultSet.getString("EmployeeID");						
						tmpPass = resultSet.getString("password");
	
					}
	
					// Close our DB Connection
					connection.close();
	
	
					if(password.equals(tmpPass) && username.equals(tmpUsername)){
	
						// Create the Session
						HttpSession session = request.getSession();
	
						// Create the Session variables
						session.setAttribute("loggedIn", true);
						session.setAttribute("EmployeeID", tmpUID);
						session.setAttribute("username", username);
						session.setAttribute("employee", user);
						
						Calendar cal = Calendar.getInstance();
						SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
						
						String ClockIn = sdf.format(cal.getTime());
						session.setAttribute("ClockIn", ClockIn);
	
	
						if(rememberMe != null){
	
							//Create Cookie if Employee checked RememberMe Box
							Cookie EmployeeCookie = new Cookie("EmployeeID", tmpUID);
							EmployeeCookie.setMaxAge(60 * 60 * 24 * 30);
							response.addCookie( EmployeeCookie );
	
						}
						
						pathToView = "/WEB-INF/login/Welcome.jsp";
						
						switch(user.getStatus()){
						case 0:
							// WAITER
							request.setAttribute("path", "/rcp-svn/Ordering");
//							request.setAttribute("path", "/cs437group01/Ordering");
							break;
						case 1:
							// HOST
							request.setAttribute("path", "/rcp-svn/HostServlet");
//							request.setAttribute("path", "/cs437group01/HostServlet");
							break;
						case 2:
							// MANAGER
							request.setAttribute("path", "/rcp-svn/Nexus");
//							request.setAttribute("path", "/cs437group01/Nexus");
							break;
						}	
	
					}else{
	
						x--;
						
						request.setAttribute("numberOfTriesLeft", x);
						request.setAttribute("action", "message1");

						pathToView = "/WEB-INF/login/Login.jsp";
	
					}					
				}
				catch(SQLException e){		
					e.printStackTrace();
				}
				catch(ClassNotFoundException e){
					e.printStackTrace();
				}	
	
	
			}
			
		}
		
		RequestDispatcher dispatcher =
				request.getRequestDispatcher( pathToView );
			
			dispatcher.forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
